package com.maserb.monitor.web.schoolStudent;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.maserb.monitor.common.*;
import com.maserb.monitor.entity.JwOrgEntity;
import com.maserb.monitor.entity.UserEntity;
import com.maserb.monitor.entity.jwQuestion.JwQuestionItemEntity;
import com.maserb.monitor.entity.schoolConduct.SchoolConductItemEntity;
import com.maserb.monitor.entity.schoolStudent.SchoolStudentEntity;
import com.maserb.monitor.entity.schoolStudent.SchoolStudentImportModel;
import com.maserb.monitor.entity.schoolStudent.SchoolStudentParentEntity;
import com.maserb.monitor.entity.schoolStudent.SchoolStudentParentImportModel;
import com.maserb.monitor.enums.SexTypeEnum;
import com.maserb.monitor.service.author_manage.UserService;
import com.maserb.monitor.service.base.IToolService;
import com.maserb.monitor.service.jwEducation.JwOrgService;
import com.maserb.monitor.service.remote.EcCardService;
import com.maserb.monitor.service.schoolStudent.SchoolStudentParentService;
import com.maserb.monitor.service.schoolStudent.SchoolStudentService;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping("/schoolStudent")
public class SchoolStudentController {


    @Autowired
    SchoolStudentService studentService;


    @Autowired
    private IToolService toolService;

    @Autowired
    JwOrgService orgService;

    @Autowired
    UserService userService;

    @Autowired
    SchoolStudentParentService parentService;

    @Autowired
    private EcCardService ecCardService;

    @Value("${monitor.studentUrl}")
    private String studentUrl;

    @RequestMapping(value = {"/initParent"})
    public void initParent() {
        studentService.initParent();
    }

    @RequestMapping(value = {"/", "/index"})
    public ModelAndView getIndex(final HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        HttpSession session = request.getSession(true);
        UserEntity user = (UserEntity) session.getAttribute("user");
        String userId = user.getId();
        List<JwOrgEntity> clazzList = new ArrayList<JwOrgEntity>();
        if(null!=user){
            clazzList = orgService.findByUser(user);
        }
        view.addObject("clazzList",clazzList);
        view.addObject("userId",userId);
        SexTypeEnum[] sexType = SexTypeEnum.values();
        view.setViewName("school_student/index");
        view.addObject("sexType",sexType);
        return view;
    }

    @RequestMapping("/doListSchoolStudent")
    @ResponseBody
    public PageResponseResult<SchoolStudentEntity> doListSchoolStudent(PageRequestParam page,final String userId, final String name, final String clazzId,final String studentId,final String schoolId,final String sex) {
        Sort.Order codeOrder = new Sort.Order(Sort.Direction.DESC, "createTime");
        List<Sort.Order> orderList = new ArrayList<Sort.Order>();
        orderList.add(codeOrder);
        Sort sort = new Sort(orderList);
        return AjaxUtils.processPage(page,sort, new Func_T1<PageRequest, Page<SchoolStudentEntity>>() {
            @Override
            public Page<SchoolStudentEntity> invoke(PageRequest var1) throws Exception {
                Page<SchoolStudentEntity> studentEntityPage = studentService.findAll(var1,userId, name,clazzId,studentId,schoolId,sex );
                for(SchoolStudentEntity entity:studentEntityPage.getContent()){
                    entity.setCreateTime(toolService.formatYYMMDDHHMMSS(entity.getCreateTime()));
                    if(!StringUtils.isEmptyOrWhitespace(entity.getSex())){
                        entity.setSexCn(SexTypeEnum.getNameByValue(Integer.parseInt(entity.getSex())));
                    }
                }
                return studentEntityPage;
            }
        });
    }



    @RequestMapping("/getAddSchoolStudent")
    public ModelAndView getAddSchoolStudent(HttpServletRequest request) {
        ModelAndView result = new ModelAndView();
        SexTypeEnum[] sexType = SexTypeEnum.values();
        List<UserEntity> userList = userService.findByOrgId(request);
        result.addObject("sexType",sexType);
        result.addObject("userList",userList);
        result.setViewName("school_student/add");
        return result;
    }

    @RequestMapping("/doAddSchoolStudent")
    @ResponseBody
    public AjaxResult<Boolean> doAddSchoolStudent(final HttpServletRequest request, SchoolStudentEntity entity) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                entity.setCreateTime(CreateTimeUtils.getCreateTime());
                if(null!=entity.getOrgId() && !"".equals(entity.getOrgId())){
                    JwOrgEntity orgEntity = orgService.findOne(entity.getOrgId());
                    entity.setOrgName(orgEntity.getName());
                    entity.setDid(orgEntity.getDid());
                }

                HttpSession session = request.getSession(true);
                UserEntity user =(UserEntity) session.getAttribute("user");
                if(null!=user){
                    entity.setSchoolId(user.getOrgId());
                    JwOrgEntity org = orgService.findOne(user.getOrgId());
                    entity.setSchoolName(org.getName());

                }else{
                    return false;
                }
                String imageUrl = entity.getSchoolId()+"\\"+entity.getStudentId()+".jpg";
                imageUrl=imageUrl.replaceAll("\\\\", "/");
                entity.setImage(imageUrl);
                entity.setIsDel("0");
                entity.setConductScore(100);
                Long cid = ecCardService.doAddPerson(entity);
                if(null!=cid){
                    entity.setCid(cid);
                }
                studentService.save(entity);
                return true;
            }
        });
    }

    @RequestMapping(value = "/export")
    public void export(HttpServletResponse response,final String userId, final String name, final String clazzId,final String studentId,final String schoolId,final String sex) {
        //模拟从数据库获取需要导出的数据
        List<SchoolStudentEntity> studentList = studentService.findAll(userId, name,clazzId,studentId,schoolId,sex );
        /*for (UserEntity entity : userLists) {
            entity.setBkfwCn(toolService.getDataTypeName("area_code", black.getBkfw()));
            entity.setFmtCreateDate(toolService.formatYYMMDDHHMMSS(black.getCreateDate()));
        }*/
        String excel_name = "学生列表";
        String fileName="";
        try{
            //fileName  = new String(name.getBytes("GBK"),"ISO-8859-1")+ System.currentTimeMillis()+".xls";
            fileName  = excel_name + System.currentTimeMillis()+".xls";
        }catch (Exception e){
            e.printStackTrace();
        }
        //导出操作
        ExcelExportUtils.exportExcel(studentList, excel_name, "", SchoolStudentEntity.class, fileName, response);
    }

    //学生导入
    @RequestMapping("/goFileUpload")
    public ModelAndView goFileUpload() {
        ModelAndView result = new ModelAndView();
        result.addObject("studentUrl",studentUrl);
        result.setViewName("school_student/student_import");
        return result;
    }


    @RequestMapping("/fileUpload")
    @ResponseBody
    public String fileUpload(final HttpServletRequest request, HttpServletResponse response, MultipartFile myfiles,String clazzId) throws IOException {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        params.setNeedVerfiy(false);
        String resultStr = "导入成功";
        HttpSession session = request.getSession(true);
        UserEntity user = (UserEntity) session.getAttribute("user");
        String orgId = "";
        String userId = "";
        if(null!=user){
            orgId = user.getOrgId();
            userId = user.getId();
        }
        try {
            ExcelImportResult result = ExcelImportUtil.importExcelMore(myfiles.getInputStream(),SchoolStudentEntity.class,params);
            List<SchoolStudentEntity> list = result.getList();
            studentService.save(list,orgId,clazzId,userId);

//            ExcelImportResult result = ExcelImportUtil.importExcelMore(myfiles.getInputStream(),SchoolStudentParentImportModel.class,params);
//            List<SchoolStudentParentImportModel> list = result.getList();
//            studentService.saveParent(list);

        } catch (Exception e) {
            return "导入失败！";
        }
        return resultStr;
    }



    //修改页面跳转
    @RequestMapping("/getUpdateSchoolStudent/{id}")
    public ModelAndView getUpdateSchoolStudent(HttpServletRequest request,@PathVariable final String id) {
        ModelAndView result = new ModelAndView();
        SchoolStudentEntity entity = studentService.findOne(id);
        SexTypeEnum[] sexType = SexTypeEnum.values();
        List<UserEntity> userList = userService.findByOrgId(request);
        result.addObject("sexType",sexType);
        result.addObject("userList",userList);
        result.setViewName("school_student/edit");
        String imageUrl = entity.getSchoolId()+"\\"+entity.getStudentId()+".jpg";
        imageUrl=imageUrl.replaceAll("\\\\", "/");
        entity.setImage(imageUrl);
        result.addObject("entity", entity);
        return result;
    }

    //修改
    @RequestMapping("/doUpdateSchoolStudent")
    @ResponseBody
    public AjaxResult<Boolean> doUpdateSchoolStudent(final HttpServletRequest request, SchoolStudentEntity entity) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                SchoolStudentEntity studentEntity = studentService.findOne(entity.getId());
                studentEntity.setName(entity.getName());
                studentEntity.setSex(entity.getSex());
                studentEntity.setBirthday(entity.getBirthday());
                studentEntity.setOrgId(entity.getOrgId());
                studentEntity.setStudentId(entity.getStudentId());
                studentEntity.setImage(entity.getImage());
                studentEntity.setIdcard(entity.getIdcard());
                studentEntity.setDescription(entity.getDescription());
                studentEntity.setUpdateTime(CreateTimeUtils.getCreateTime());
                studentEntity.setMaster(entity.getMaster());
                studentEntity.setParent(entity.getParent());
                studentEntity.setCardNumber(entity.getCardNumber());
                if(null!=entity.getOrgId() && !"".equals(entity.getOrgId())){
                    JwOrgEntity orgEntity = orgService.findOne(entity.getOrgId());
                    studentEntity.setOrgName(orgEntity.getName());
                    studentEntity.setDid(orgEntity.getDid());
                }
                String imageUrl = entity.getSchoolId()+"\\"+entity.getStudentId()+".jpg";
                imageUrl=imageUrl.replaceAll("\\\\", "/");
                entity.setImage(imageUrl);
                studentService.save(studentEntity);
                ecCardService.doUpdatePerson(studentEntity);
                return true;
            }
        });
    }

    //删除
    @RequestMapping("/doDeleteSchoolStudent")
    @ResponseBody
    public AjaxResult<Boolean> doDeleteSchoolStudent(@RequestParam(value = "keys[]") ArrayList<String> keys)
    {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                /*keys.forEach(id -> studentService.delete(id));*/
                if(null!=keys && keys.size()>0){
                    for(int i=0;i<keys.size();i++){
                        SchoolStudentEntity entity = studentService.findOne(keys.get(i));
                        ecCardService.doDeletePerson(entity);
                        studentService.delete(keys.get(i));
                    }
                }
                return true;
            }
        });
    }

    //App调用

    /**
     * 班级学生列表
     * @param clazzId
     * @return
     */
    @RequestMapping("/studentList")
    @ResponseBody
    public AjaxResult<List<SchoolStudentEntity>> studentList(final String clazzId)
    {
        return AjaxUtils.process(new Func_T<List<SchoolStudentEntity>>() {
            @Override
            public List<SchoolStudentEntity> invoke() throws Exception {
                return studentService.findByClazzId(clazzId);
            }
        });
    }

    /**
     * 按学号或姓名查询班级学生
     * @param clazzId
     * @return
     */
    @RequestMapping("/studentListByNameOrId")
    @ResponseBody
    public AjaxResult<List<SchoolStudentEntity>> studentListByNameOrId(final String clazzId,final String nameOrId)
    {
        return AjaxUtils.process(new Func_T<List<SchoolStudentEntity>>() {
            @Override
            public List<SchoolStudentEntity> invoke() throws Exception {
                return studentService.studentListByNameOrId(clazzId,nameOrId);
            }
        });
    }



    /**
     * 学生详情
     * @param id
     * @return
     */
    @RequestMapping("/studentDetail")
    @ResponseBody
    public AjaxResult<SchoolStudentEntity> studentDetail(final String id)
    {
        return AjaxUtils.process(new Func_T<SchoolStudentEntity>() {
            @Override
            public SchoolStudentEntity invoke() throws Exception {
                return studentService.findOne(id);
            }
        });
    }

    /**
     * 学生评价列表
     * @param clazzId
     * @return
     */
        @RequestMapping("/studentEvaluationList")
    @ResponseBody
    public AjaxResult<List<SchoolStudentEntity>> studentEvaluationList(final String clazzId)
    {
        return AjaxUtils.process(new Func_T<List<SchoolStudentEntity>>() {
            @Override
            public List<SchoolStudentEntity> invoke() throws Exception {
                return studentService.findByClazzIdWithScore(clazzId);
            }
        });
    }



    /**
     * 学生评价详情
     * @param id
     * @return
     */
    @RequestMapping("/studentEvaluationDetail")
    @ResponseBody
    public AjaxResult<SchoolStudentEntity> studentEvaluationDetail(final String id)
    {
        return AjaxUtils.process(new Func_T<SchoolStudentEntity>() {
            @Override
            public SchoolStudentEntity invoke() throws Exception {
                SchoolStudentEntity student = studentService.findOne(id);
                studentService.getStudentScore(student);

                return student;
            }
        });
    }

    /*//导出
    @RequestMapping("/getExportSchoolStudent")
    public void getExportSchoolStudent(HttpServletResponse response, @RequestParam String id) {
        SchoolStudentEntity SchoolStudentEntity = studentService.findOne(id);
        List<SchoolStudentItemEntity> list =SchoolStudentEntity.getItems();
        String name=SchoolStudentEntity.getName();
        String fileName="";
        try{
            fileName  = name + System.currentTimeMillis()+".xls";
        }catch (Exception e){
            e.printStackTrace();
        }
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(name, name),
                SchoolStudentItemEntity.class, list);
        ExcelExportUtils.downLoadExcel(fileName, response, workbook);
    }

    //导入
    @RequestMapping("/goFileUpload")
    public ModelAndView goFileUpload() {
        ModelAndView result = new ModelAndView();
        result.setViewName("school_conduct/SchoolStudent_import");
        return result;
    }


    @RequestMapping("/fileUpload")
    @ResponseBody
    public String fileUpload(final HttpServletRequest request,HttpServletResponse response, MultipartFile myfiles) throws IOException {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        params.setNeedVerfiy(true);
        String resultStr = "导入成功";
        try {
            ExcelImportResult result = ExcelImportUtil.importExcelMore(myfiles.getInputStream(),SchoolStudentItemEntity.class,params);
            List<SchoolStudentItemEntity> list = result.getList();
            Sheet sheet = result.getWorkbook().getSheetAt(0);
            String sheetName = sheet.getSheetName();
            String title =sheet.getRow(0).getCell(0).getStringCellValue();
            studentService.saveImport(title,list);
        } catch (Exception e) {
            return "导入失败！";
        }
        return resultStr;
    }*/


}
